package cn.dengl.sky.springboot.common.config.druid;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @program: springboot
 * @description: 第二个数据源
 * @author: dengl
 * @create: 2018-10-09 09:57
 */
@Configuration
@MapperScan(basePackages = {"cn.dengl.sky.springboot.db2.dao"},sqlSessionTemplateRef = "db2SqlSessionTemplate")
public class DruidConfiguration2 {
    @Value("${spring.ds.db2.mapper-locations}")
    private String mapperLOcation;
    @Bean(name="db2DataSource")
    @ConfigurationProperties(prefix = "spring.ds.db2")

    public DataSource db2DataSource(){
//        return DataSourceBuilder.create().build();
        return new DruidDataSource();
    }
    @Bean(name="db2TransactionManager")
    public DataSourceTransactionManager setTransactionManager(@Qualifier("db2DataSource") DataSource dataSource){
        return  new DataSourceTransactionManager(dataSource);
    }
    @Bean (name="db2SqlSessionFactory")
    public SqlSessionFactory setSqlSessionFactory(@Qualifier("db2DataSource") DataSource dataSource) throws Exception{
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLOcation));
        return bean.getObject();
    }
    @Bean(name="db2SqlSessionTemplate")
    public SqlSessionTemplate setSqlSessionTemplate(@Qualifier("db2SqlSessionFactory")SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }


}
